package ecoll.server.quiz;

import java.util.ArrayList;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import ecoll.client.quiz.QuizService;
import ecoll.client.quiz.QuizUserData;

@SuppressWarnings("serial")
public class QuizServiceImpl extends RemoteServiceServlet implements
		QuizService {

	@Override
	public String createRoom(String roomName, int period, int delay,
			ArrayList<Long> files) {
		/*
		 * Thread thread = ThreadManager.createBackgroundThread(new Runnable() {
		 * public void run() { try { while (true) { Thread.sleep(10); } } catch
		 * (InterruptedException ex) { throw new
		 * RuntimeException("Interrupted in loop:", ex); } } }); thread.start();
		 */

		if (!roomName.matches("[a-zA-Z\\d_-]{1,20}"))
			return null;
		Key roomKey = QuizDatabase.putRoom(roomName, period, delay, files);
		if (roomKey == null)
			return null;
		QuizRoom newRoom = QuizDatabase.getRoom(roomName);
		// rooms.putIfAbsent(roomName, newRoom);
		if (newRoom == null)
			return null;

		QuizTaskServlet.schedule(roomName, newRoom.getRoundId(), 5, false);
		return newRoom.join();
	}

	@Override
	public String joinRoom(String roomName) {
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room == null)
			return null;
		return room.join();
	}

	@Override
	public void leaveRoom(String roomName) {
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room == null)
			return;
		room.leave();
	}

	@Override
	public ArrayList<QuizUserData> getRanking(String roomName) {
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room == null)
			return null;
		return room.getRanking();
	}

	@Override
	public Boolean userActivity(String roomName, String activity) {
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room == null)
			return null;
		return room.answer(activity);
	}

	@Override
	public String getQuestion(String roomName) {
		QuizRoom room = QuizDatabase.getRoom(roomName);
		if (room == null)
			return null;
		return room.getQuestion();
	}

	// private ConcurrentSkipListMap<String, QuizRoom> rooms = new
	// ConcurrentSkipListMap<String, QuizRoom>();

}
